<template>
  <a-card :title="$t('Survey Review')">
    <a-table bordered :dataSource="dataSource" :columns="columns">
      <template #bodyCell="{ column, record }">

        <template v-if="column.key === 'auditStatus'">
          <a-tag :color="'green'"> {{record.auditStatus}} </a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-button type="link" @click="checkSurvey(record, 'audit')">{{$t("Start Survey")}}</a-button>
        </template>
      </template>
    </a-table>
  </a-card>
  <a-modal v-model:open="open" :title="currentSurvey?.title" width="50vw">
    <a-form layout="vertical">
      <a-form-item>
        <p>{{$t('Survey Points')}}: {{currentSurvey.points}}  &nbsp;&nbsp;&nbsp;&nbsp; {{$t('Expiration Time')}}: {{currentSurvey.expireTime}}</p>
      </a-form-item>
      <a-form-item v-for="(item, index) in currentSurvey.questions" :key="item.id" :label="`${index + 1}.${item.question}`">
        <a-radio-group v-model:value="item.userAnswer" v-if="item.questionType === 0 || item.questionType === '0'" @change="saveCurrentAnswer(item)">
          <a-radio v-for="option in item.options" :key="option.id" :value="option.questionOption">{{option.questionOption}}. {{option.content}}</a-radio>
        </a-radio-group>
        <a-checkbox-group v-model:value="item.userAnswer" v-if="item.questionType === 1 || item.questionType === '1'" name="checkboxgroup" @change="saveCurrentAnswer(item)">
          <a-checkbox v-for="option in item.options" :key="option.id" :value="option.questionOption">{{option.questionOption}}. {{option.content}}</a-checkbox>
        </a-checkbox-group>
        <a-textarea v-model:value="item.userAnswer" v-if="item.questionType === 2 || item.questionType === '2'" style="max-height:100px;min-height:100px" :rows="4" @blur="saveCurrentAnswer(item)" />
      </a-form-item>

    </a-form>
    <template #footer>
      <a-space>
        <a-button @click="open = false">{{$t('Save')}}</a-button>
        <a-button type="primary" v-if="handleType === 'audit'" @click="submitSurvey">{{$t('Submit')}}</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script lang="ts" setup>
import {
  AuditOutlined,
  EditOutlined,
  SearchOutlined,
} from "@ant-design/icons-vue";
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import { message } from "ant-design-vue";

const { t } = useI18n();
import { auditSurveyDetail, getList, startSurvey, finishSurvey, saveProgress} from "../../api/survey";
const dataSource = ref([]);
const columns = ref([
  { title: t("Survey Title"), dataIndex: "title", key: "title", ellipsis: true},
  { title: t("Survey Points"), dataIndex: "points", key: "points", width: 200 },
  { title: t('Expiration Time'), dataIndex: "expireTime",  key: "expireTime",  width: 200, },
  { title: t("Action"), dataIndex: "action", key: "action", width: 200, align: 'center'},
]);
const userInfo = JSON.parse(window.localStorage.getItem("user_info"));

const open = ref<boolean>(false);
const handleType = ref<string>();
const currentSurvey = ref();
const currentUserSurveyId = ref()
const checkSurvey = (item: any, type: string) => {
  startSurvey({surveyId: item.id}).then(res => {
    if (res.status == 200) {
      if(!res.data.flag){
        open.value = false;
        message.warning(res.data.msg)
        return;
      }
       currentUserSurveyId.value = item.userSurveyId
        open.value = true;
        handleType.value = type;
        currentSurvey.value = res.data.data;
        currentSurvey.value.questions.map(item => {
          if(item.questionType === 1 || item.questionType === "1"){
            item.userAnswer = item.userAnswer?.split(",")
          }
        })
      // auditSurveyDetail({userId: userInfo.userId, surveyId: item.id}).then(res => {
      //   if (res.status == 200) {
           
      //   }
      // })
    }
  })
};

const submitSurvey = () => {
  finishSurvey({surveyId: currentSurvey.value.id}).then(response => {
    if (response.status == 200) {
      open.value = false;
    }
  });
}

let timer = null;
let times = 0;
let currentQuestion = '';
let oldParams = []
const saveCurrentAnswer = (item => {
    let userAnswer = item.questionType === 1 || item.questionType === "1" ? item.userAnswer.join(",") : item.userAnswer 
    let params = {
      "surveyId": item.surveyId,
      "questionId": item.id,
      "userAnswer": userAnswer
    }
  saveProgress(params).then(res => {
          if(res.status == 200) {
            oldParams[0] = params
            currentQuestion = item.id
          }
  })
})

const querySurveyList = () => {
  let params = {};
  getList(params).then((res) => {
    if (res?.status == 200) {
      dataSource.value = res?.data?.data?.rows;
    }
  });
};

querySurveyList();
</script>
<style scoped>
.servey-list {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}
.servey-list-item {
  width: 22.5%;
  margin-bottom: 20px;
}
</style>